<?php

/**
 * This file is part of the Codizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Codizer Core Team <team@codizer.org>
 * @package     Codizer
 */

class f_builder_ApplicationBuilder
{
	/**
	 * Get instance
	 *
	 * @return f_builder_ApplicationBuilder
	 */
	public static function getInstance()
	{
		return new self();	
	}
	
	/**
	 * Main method to create application folders
	 *
	 */
	public function initApplication()
	{
		$dirs = array(	'modules',
						'webapp',
						'webapp/cache',
						'webapp/cache/templates_c',
						'webapp/cache/html',
						'webapp/config',
						'webapp/logs',
						'webapp/modules',
                        'webapp/pkg',
						'www'
						);
		
		$basePath = BASE_DIR.DS;
		
		foreach($dirs as $dir)
		{
			if(!is_dir($basePath.$dir))
			{				
				if(mkdir($basePath.$dir, 0775, true))
				{
                    if(CLI_MODE) echo COLOR_GREEN.'Writing'.COLOR_NORMAL.' -> create path '.$basePath.$dir."\r\n";
				}
				else
				{
					if(CLI_MODE) echo COLOR_RED.'Error'.COLOR_NORMAL.'  -> Error in '.$basePath.$dir.' creation'. "\r\n";
				}
			}
			else
			{
				if(CLI_MODE) echo COLOR_RED.'Writing'.COLOR_NORMAL.' -> '.$basePath.$dir.' already exists'."\r\n";
			}
		}
		
		$this->copyDefaultDocuments();
	}
	
	/**
	 * Copy/create default documents
	 */
	private function copyDefaultDocuments()
	{
		// Special case : for user

		if(!is_null($this->getUser()))
		{
			$file = CONFIG_DIR.DS.'config.'.$this->getUser().'.ini';
			if(!is_file($file))
			{
				$this->copyDefaultDocument('config.example.ini', $file);
			}
		}
        
		$documents = array(	'config.example.ini' => CONFIG_DIR.DS.'config.prod.ini',
							'routing.xml' => CONFIG_DIR.DS.'routing.xml',
							'index.php' => BASE_DIR.DS.'www'.DS.'index.php',
							'htaccess' => BASE_DIR.DS.'www'.DS.'.htaccess');

		foreach($documents as $document => $destination)
		{
			if(!is_file($destination))
			{
				$this->copyDefaultDocument($document, $destination);
			}
		}	
	}
	
	/**
	 * Copy one default document to given destination
	 *
	 * @param string $documentName
	 * @param string $destinationPath
	 * @return boolean
	 */
	private function copyDefaultDocument($documentName, $destinationPath)
	{
		$documentPath = FRAMEWORK_HOME.DS.'builder'.DS.'defaultdocuments'.DS;

		if(CLI_MODE) echo COLOR_GREEN.'Copy'.COLOR_NORMAL.'    -> '.$documentName.' copied into '.$destinationPath."\r\n";
		return copy($documentPath.$documentName, $destinationPath);
	}
	
	/**
	 * Get user defined in userProfile
	 *
	 * @return string
	 */
	private function getUser()
	{
		return f_loader_Config::getSuffixFromUserProfile();
	}
}